package com.dabai.puzzle;

import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.DiffUtil;
import androidx.recyclerview.widget.DividerItemDecoration;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.bumptech.glide.Glide;
import com.dabai.dbutils.dialog.MdcDialog;
import com.dabai.dbutils.dialog.TipAlertDialog;
import com.dabai.dbutils.toast.DBToast;
import com.dabai.dbutils.utils.AppUtils;
import com.dabai.dbutils.utils.FileUtils;
import com.dabai.dbutils.utils.NotificationUtils;
import com.dabai.dbutils.utils.SAFUtils;
import com.dabai.dbutils.utils.UriUtils;
import com.dabai.puzzle.adapter.PhotoAdapter;
import com.dabai.puzzle.bean.PhotoInfo;
import com.dabai.puzzle.utils.BitmapUtils;
import com.dabai.puzzle.utils.ScreenUtils;
import com.dabai.uitools.utils.DisplayUtils;
import com.dabai.uitools.view.OverRecyclerViewLayout;
import com.edmodo.cropper.CropImageView;
import com.google.android.material.dialog.MaterialAlertDialogBuilder;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import com.permissionx.guolindev.PermissionX;
import com.zhihu.matisse.Matisse;
import com.zhihu.matisse.MimeType;
import com.zhihu.matisse.engine.impl.GlideEngine;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.concurrent.ExecutionException;

public class MainActivity extends AppCompatActivity {

    private FloatingActionButton mAddbutton;
    private FloatingActionButton mSavebutton;
    private TextView mTextview;
    private RecyclerView mRecyclerview;


    Context context;
    private PhotoAdapter photoAdapter;
    private ArrayList<PhotoInfo> photoList;
    private OverRecyclerViewLayout mOverrecycler;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        context = this;
        initViews();

        PermissionX.init(this)
                .permissions(Manifest.permission.WRITE_EXTERNAL_STORAGE)
                .request((allGranted, grantedList, deniedList) -> {
                    if (!allGranted) {
                        DBToast.showText(context, "无储存权限，不能保存到外部目录。", false);
                        finish();
                    }
                });

        TipAlertDialog.init(context);

        mRecyclerview.setLayoutManager(new LinearLayoutManager(this));
        mRecyclerview.addItemDecoration(new DividerItemDecoration(context, LinearLayout.VERTICAL));

        photoAdapter = new PhotoAdapter(R.layout.item_photo);
        mRecyclerview.setAdapter(photoAdapter);

        photoList = new ArrayList<>();

        Matisse.from(MainActivity.this)
                .choose(MimeType.of(MimeType.PNG, MimeType.JPEG), false) // 选择 mime 的类型
                .showSingleMediaType(true)
                .countable(true)
                .maxSelectable(20) // 图片选择的最多数量
                .restrictOrientation(ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED)
                .thumbnailScale(0.85f) // 缩略图的比例
                .imageEngine(new GlideEngine()) // 使用的图片加载引擎
                .forResult(101); // 设置作为标记的请求码


        mAddbutton.setOnLongClickListener(v -> {

            Matisse.from(MainActivity.this)
                    .choose(MimeType.of(MimeType.PNG, MimeType.JPEG), false) // 选择 mime 的类型
                    .showSingleMediaType(true)
                    .countable(true)
                    .maxSelectable(20) // 图片选择的最多数量
                    .restrictOrientation(ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED)
                    .thumbnailScale(0.85f) // 缩略图的比例
                    .imageEngine(new GlideEngine()) // 使用的图片加载引擎
                    .forResult(101); // 设置作为标记的请求码

            return true;
        });

        mAddbutton.setOnClickListener(v -> {

            Matisse.from(MainActivity.this)
                    .choose(MimeType.of(MimeType.PNG, MimeType.JPEG), false) // 选择 mime 的类型
                    .showSingleMediaType(true)
                    .countable(true)
                    .maxSelectable(30) // 图片选择的最多数量
                    .restrictOrientation(ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED)
                    .thumbnailScale(0.85f) // 缩略图的比例
                    .imageEngine(new GlideEngine()) // 使用的图片加载引擎
                    .forResult(102); // 设置作为标记的请求码

        });

        mSavebutton.setOnClickListener(v -> {

            if (photoAdapter.getData().size() <= 0) {
                DBToast.showYellowToast(context, "没东西~");
                return;
            }

            new MaterialAlertDialogBuilder(context)
                    .setItems(new String[]{"保存图片并打开微信", "保存图片并打开QQ", "保存图片"}, (dialog, which) -> {
                        if (which == 0) {

                            TipAlertDialog.getInstance(context).showTipLayout("正在保存...");

                            new Thread(() -> {

                                Bitmap bitmap = null;

                                for (PhotoInfo photoInfo : photoAdapter.getData()) {
                                    if (bitmap == null) {
                                        bitmap = photoInfo.getBitmap();
                                    } else {
                                        bitmap = BitmapUtils.bitmapVerticalSplices(bitmap, photoInfo.getBitmap());
                                    }
                                }
                                boolean isOk = FileUtils.saveBitmapToDCIM(context, bitmap, "Puzzle", "Puzzle_" + new Random().nextInt(100000));

                                runOnUiThread(() -> {
                                    TipAlertDialog.getInstance(context).hideTipLayout();
                                    DBToast.showMethodsFeedbackText(context, isOk, "图片保存成功!", "保存失败!");

                                    AppUtils.openApp(context, "com.tencent.mm");
                                });
                            }).start();


                        }
                        if (which == 1) {


                            TipAlertDialog.getInstance(context).showTipLayout("正在保存...");

                            new Thread(() -> {

                                Bitmap bitmap = null;

                                for (PhotoInfo photoInfo : photoAdapter.getData()) {
                                    if (bitmap == null) {
                                        bitmap = photoInfo.getBitmap();
                                    } else {
                                        bitmap = BitmapUtils.bitmapVerticalSplices(bitmap, photoInfo.getBitmap());
                                    }
                                }
                                boolean isOk = FileUtils.saveBitmapToDCIM(context, bitmap, "Puzzle", "Puzzle_" + new Random().nextInt(100000));

                                runOnUiThread(() -> {
                                    TipAlertDialog.getInstance(context).hideTipLayout();
                                    DBToast.showMethodsFeedbackText(context, isOk, "图片保存成功!", "保存失败!");

                                    AppUtils.openApp(context, "com.tencent.mobileqq");
                                });
                            }).start();


                        }
                        if (which == 2) {

                            TipAlertDialog.getInstance(context).showTipLayout("正在保存...");

                            new Thread(() -> {

                                Bitmap bitmap = null;

                                for (PhotoInfo photoInfo : photoAdapter.getData()) {
                                    if (bitmap == null) {
                                        bitmap = photoInfo.getBitmap();
                                    } else {
                                        bitmap = BitmapUtils.bitmapVerticalSplices(bitmap, photoInfo.getBitmap());
                                    }
                                }
                                boolean isOk = FileUtils.saveBitmapToDCIM(context, bitmap, "Puzzle", "Puzzle_" + new Random().nextInt(100000));

                                runOnUiThread(() -> {
                                    TipAlertDialog.getInstance(context).hideTipLayout();
                                    DBToast.showMethodsFeedbackText(context, isOk, "图片保存成功!", "保存失败!");
                                });
                            }).start();

                        }


                    }).show().getWindow().setWindowAnimations(com.dabai.uitools.R.style.DBAnim_Transitions_Via);

        });


        photoAdapter.setOnItemClickListener((adapter, view, position) -> {
            PhotoInfo photoInfo = (PhotoInfo) adapter.getData().get(position);

            CropImageView cropImageView = new CropImageView(context);
            cropImageView.setImageBitmap(photoInfo.getBitmap());


            new MaterialAlertDialogBuilder(context)
                    .setTitle("裁剪图片")
                    .setView(cropImageView)
                    .setNeutralButton("取消", null)
                    .setPositiveButton("裁剪", (dialog, which) -> {
                        Bitmap cropBitmap = cropImageView.getCroppedImage();

                        photoAdapter.setData(position, new PhotoInfo(cropBitmap, photoInfo.getUri()));

                    })
                    .show().getWindow().setWindowAnimations(com.dabai.uitools.R.style.DBAnim_Transitions_Via);

        });

        photoAdapter.setOnItemLongClickListener((adapter, view, position) -> {
            PhotoInfo photoInfo = (PhotoInfo) adapter.getData().get(position);

            new MaterialAlertDialogBuilder(context)
                    .setTitle("单图操作")
                    .setItems(new String[]{"裁剪顶部(状态栏高度)", "还原图片", "保存单图"}, (dialog, which) -> {
                        if (which == 0) {

                            new Thread(new Runnable() {

                                private PhotoInfo photoInfo1;

                                @Override
                                public void run() {
                                    photoInfo1 = new PhotoInfo(BitmapUtils.bitmapCuttingTop(photoInfo.getBitmap(), DisplayUtils.getStatusBarHeight(context)), photoInfo.getUri());
                                    runOnUiThread(() -> photoAdapter.setData(position, photoInfo1));
                                }
                            }).start();

                        }
                        if (which == 1) {

                            new Thread(new Runnable() {

                                private PhotoInfo photoInfo1;

                                @Override
                                public void run() {
                                    try {
                                        photoInfo1 = new PhotoInfo(Glide.with(context)
                                                .asBitmap()
                                                .load(photoInfo.getUri()).submit().get(), photoInfo.getUri());
                                    } catch (ExecutionException | InterruptedException ignored) {
                                    }

                                    runOnUiThread(() -> photoAdapter.setData(position, photoInfo1));
                                }
                            }).start();

                        }
                        if (which == 2) {
                            boolean isOk = FileUtils.saveBitmapToDCIM(context, photoInfo.getBitmap(), "Puzzle", "Puzzle_" + new Random().nextInt(100000));
                            DBToast.showMethodsFeedbackText(context, isOk, "保存成功!", "保存失败!");
                        }
                    }).show().getWindow().setWindowAnimations(com.dabai.uitools.R.style.DBAnim_Transitions_Via);

            return true;
        });

    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (requestCode == 101 && resultCode == RESULT_OK) {
            if (data != null) {

                List<Uri> mSelected = Matisse.obtainResult(data);

                photoList = new ArrayList<>();
                TipAlertDialog.getInstance(context).showTipLayout("正在载入源文件...");

                new Thread(() -> {

                    for (Uri uri : mSelected) {

                        try {
                            photoList.add(new PhotoInfo(Glide.with(context)
                                    .asBitmap()
                                    .load(uri).submit().get(), uri));
                        } catch (ExecutionException | InterruptedException ignored) {
                        }

                    }

                    runOnUiThread(() -> {

                        photoAdapter.setDiffCallback(new DiffUtil.ItemCallback<PhotoInfo>() {
                            @Override
                            public boolean areItemsTheSame(@NonNull PhotoInfo oldItem, @NonNull PhotoInfo newItem) {
                                return false;
                            }

                            @Override
                            public boolean areContentsTheSame(@NonNull PhotoInfo oldItem, @NonNull PhotoInfo newItem) {
                                return false;
                            }
                        });
                        photoAdapter.setDiffNewData(photoList);
                        photoAdapter.notifyDataSetChanged();
                        refTitle();

                        TipAlertDialog.getInstance(context).hideTipLayout();

                    });
                }).start();

            }
        }

        if (requestCode == 102 && resultCode == RESULT_OK) {
            if (data != null) {

                List<Uri> mSelected = Matisse.obtainResult(data);

                ArrayList<PhotoInfo> addList = new ArrayList<>();

                new Thread(() -> {

                    for (Uri uri : mSelected) {

                        try {
                            addList.add(new PhotoInfo(Glide.with(context)
                                    .asBitmap()
                                    .load(uri).submit().get(), uri));
                        } catch (ExecutionException | InterruptedException ignored) {
                        }

                    }

                    runOnUiThread(() -> {

                        photoAdapter.addData(addList);
                        photoAdapter.notifyDataSetChanged();
                        refTitle();

                    });
                }).start();

            }
        }
    }

    private void refTitle() {
        setTitle("图片数量:" + photoAdapter.getData().size());
    }

    private void initViews() {
        mAddbutton = findViewById(R.id.addButton);
        mSavebutton = findViewById(R.id.saveButton);
        mTextview = findViewById(R.id.textView);
        mRecyclerview = findViewById(R.id.recyclerView);
        mOverrecycler = findViewById(R.id.overRecycler);
    }

    // 用来计算返回键的点击间隔时间
    private long exitTime = 0;

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK
                && event.getAction() == KeyEvent.ACTION_DOWN) {
            if ((System.currentTimeMillis() - exitTime) > 2000) {
                //弹出提示，可以有多种方式
                DBToast.showYellowToast(context, "再按一次退出程序");
                exitTime = System.currentTimeMillis();
            } else {
                finish();
            }
            return true;
        }

        return super.onKeyDown(keyCode, event);
    }

    @Override
    protected void onDestroy() {
        TipAlertDialog.destroyTipLayout();
        super.onDestroy();
    }


    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        int itemId = item.getItemId();
        if (itemId == R.id.allCropState) {

            new Thread(() -> {

                for (int i = 0; i < photoAdapter.getData().size(); i++) {
                    PhotoInfo photoInfo = photoAdapter.getItem(i);
                    PhotoInfo photoInfo1 = new PhotoInfo(BitmapUtils.bitmapCuttingTop(photoInfo.getBitmap(), DisplayUtils.getStatusBarHeight(context)), photoInfo.getUri());
                    int finalI = i;
                    runOnUiThread(() -> photoAdapter.setData(finalI, photoInfo1));
                }
            }).start();


            return true;
        } else if (itemId == R.id.allReset) {
            new Thread(() -> {

                for (int i = 0; i < photoAdapter.getData().size(); i++) {
                    PhotoInfo photoInfo = photoAdapter.getItem(i);

                    try {
                        PhotoInfo photoInfo1 = new PhotoInfo(Glide.with(context)
                                .asBitmap()
                                .load(photoInfo.getUri()).submit().get(), photoInfo.getUri());
                        int finalI = i;
                        runOnUiThread(() -> photoAdapter.setData(finalI, photoInfo1));
                    } catch (ExecutionException | InterruptedException ignored) {
                    }


                }
            }).start();

            return true;
        }else if (itemId == R.id.delPuzzle) {

            File file = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM),"Puzzle");

            MdcDialog.showConfirmDialog(context, "提示", "确定删除"+FileUtils.getDir(file).list().length+"张拼接图嘛?", new MdcDialog.OnConfirmDialogButtonListener() {
                @Override
                public void confirm() {

                    DBToast.showMethodsFeedbackText(context,FileUtils.delete(file),"删除成功!","删除失败!");

                }
                @Override
                public void cancel() {

                }
            }).getWindow().setWindowAnimations(com.dabai.uitools.R.style.DBAnim_Transitions_Via);

            return true;
        }
        return super.onOptionsItemSelected(item);
    }


    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.main, menu);
        return super.onCreateOptionsMenu(menu);
    }
}